<!-- 商品设置 -->
<template>
    <div >
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`${classifyItem.cateName}-商品配置`"
            @back="() => $router.go(-1)"
        >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="商品名称">
                            <a-input v-model="name" allow-clear placeholder="请输入商品名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24" v-if="showClassify">
                        <a-form-item label="商品分类">
                            <a-select v-model="cateId" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item) in classifyList" :key="item.id" :value="item.id">{{item.cateName}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24' v-else>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button style="margin-right: 20px" type="primary" @click="getData()">查询</a-button>
                            <a-button icon="plus" @click="add()">公共区一级新增</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  
        <a-table size="small" :columns="columns" :data-source="dataList" :loading="isload" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" @change="handleTableChange">
            <!-- <a-avatar  slot="imageUrl" slot-scope="imageUrl" :src="imageUrl" /> -->
            <div slot="imageUrl" slot-scope="imageUrl">
                <img style="width: 100px;height: 50px" :src="imageUrl" alt="">
            </div>
            <div slot="carouselPicture" slot-scope="carouselPicture">
                <img v-if="carouselPicture.length > 0" style="width: 100px;height: 50px" :src="carouselPicture[0]" alt="">
                <div v-else>-</div>
            </div>
            <div slot="detailsPicture" slot-scope="detailsPicture">
                <img v-if="detailsPicture.length > 0" style="width: 100px;height: 50px" :src="detailsPicture[0]" alt="">
                <div v-else>-</div>
            </div>
            <!-- <div slot="colorId" slot-scope="colorId">
                <div v-for="(item,i) in colorsList" :key="i">
                    <a-tag v-if="item.id == colorId" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div> -->
            <div slot="cateId" slot-scope="cateId">
                <div v-for="(item,i) in classifyList" :key="i">
                    <a-tag v-if="item.id == cateId" :color="colors[i%13]">{{item.cateName}}</a-tag>
                </div>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="上架" un-checked-children="下架" disabled :checked="status == 1 ? true : false" />
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="detail(record)">查看</a-button>
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <a-popconfirm
                        title="是否确认删除当前数据?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button class="errorColor" type="link">删除</a-button>
                    </a-popconfirm>
                </div>
            </template>
        </a-table>
        </a-page-header>

        <!-- 增删改商品设置 -->
        <a-modal
            title="添加、修改商品设置"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="商品名称">
                        <a-input v-model="item.name" placeholder="请输入商品名称" allow-clear></a-input>
                    </a-form-item>
                    <!-- <a-form-item label="商品分类">
                        <a-select v-model="item.cateId" placeholder="请选择">
                            <a-select-option v-for="(item) in classifyList" :value="item.id.toString()" :key="item.id">{{item.cateName}}</a-select-option>
                        </a-select>       
                    </a-form-item> -->
                    <!-- <a-form-item label="颜色">
                         <a-select v-model="item.colorId" placeholder="请选择">
                            <a-select-option v-for="(item) in colorsList" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                         </a-select>       
                     </a-form-item> -->
                    <a-form-item label="商品排序" help="值越大，商品余越靠前">
                        <a-input v-model="item.sort" placeholder="请输入商品排序" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="图片">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            
                            @change="handleChange"
                            >
                            <div v-if="fileList.length < 1">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="商品主图">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList1"
                            @preview="handlePreview"
                            @change="handleChange1"
                            >
                            <div v-if="fileList1.length < 10">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="商品详情图">
                        <a-tag color="#f50">
                            修改时，如果上传图片就会覆盖掉之前的图片，如果不修改就无需上传
                        </a-tag>
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList2"
                            @preview="handlePreview"
                            @change="handleChange2"
                            >
                            <div v-if="fileList2.length < 10">
                                <a-icon type="plus" />
                                <div class="ant-upload-text">
                                    选择图片
                                </div>
                            </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="是否上架">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>


        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryClassify } from '@/api/mall/classify';
import { queryGoodsGeneral , updateGoodsGeneral , queryGoodsCommonConfig } from '@/api/newMall';
import { queryGoodsPicture , updateGoodsPicture } from '@/api/mall/picture';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            classifyItem: JSON.parse(localStorage.getItem('classifyItem')),
            name: this.$route.query.goodsName ?? '', // 商品名称
            showClassify: this.$route.query.goodsName !== null && this.$route.query.goodsName !== undefined ? true : false,
            cateId: JSON.parse(localStorage.getItem('classifyItem')).id,
            classifyList: [],
            colorId: undefined,
            colorsList: [],
            status: undefined,
            statusList: [
                { id: '0', name: '下架'},
                { id: '1', name: '上架'},
            ],
            page: 1,
            size: 10,
            total: 0,
            dataList: [],
            isload: false,
            confirmLoading: false,
            visible: false,
            columns,
            item: {
                id: '',
                name: '', // 商品名称
                colorId: undefined, // 颜色ID
                cateId: undefined, // 分类ID
                sort: '99', // 排序
                status: '1', // 状态，1：上架，0：下架
            },
            fileList: [],
            fileList1: [],
            fileList2: [],
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            previewImage: '',
            previewVisible: false,
            carouselPicture: [],
            detailsPicture: [],
        };
    },
    async created(){
        try {
            await this.getClassify();
            await this.getColors();
            this.getData();
        } catch (error) {
            _this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        // 获取商品设置
        getData(){
            let _this = this;
            const params = {
                'brandId': _this.brandId,
                'name': _this.name,
                'cateId': _this.cateId,
                'colorId': _this.colorId,
                'status': _this.status,
                'page': _this.page - 1,
                'size': _this.size,
            }
            _this.isload = true;
            queryGoodsGeneral(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.content;
                    _this.total = res.data.totalElements
                    console.log(_this.dataList,'datalIST')
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 获取分类信息
        async getClassify(){
            let _this = this;
            try {
                const params = {
                    'brandId':_this.brandId,
                    'level':'2',
                    'size': 99,
                    'page': 0,
                }
                _this.classifyList = await _this._queryClassify(params,)
            } catch (error) {
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
            }
        },
        _queryClassify(params,type){
            var _this=this
            return new Promise((resolve,reject) => {
                queryClassify(params)
                .then(res=>{
                    if(res.success){
                        resolve(res.data.content)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 获取颜色信息
        getColors(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'page': 0,
                    'size': 99,
                    'status': '1',
                    'type': '2'
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        _this.colorsList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.item.id = ''
            this.item.name = ''
            this.item.cateId = this.classifyItem.id;
            this.item.colorId = undefined;
            this.item.sort = 99;
            this.item.status = '1';
            this.fileList = [];
            this.fileList1 = [];
            this.fileList2 = [];
            this.visible = true;
        },
        // 修改
        update(item){
            this.item = JSON.parse(JSON.stringify(item))
            this.fileList = [];
            if(item.imageUrl != '' && item.imageUrl != null){
                this.fileList.push({
                    'uid': item.id,
                    'id': item.id,
                    'url': item.imageUrl,
                    'goodsId': item.id,
                    'status':'done',
                    'name':'image.png',
                    'isUrl': true,
                })
            }
            this._queryGoodsPicture(item.id,'0')
            this._queryGoodsPicture(item.id,'1')
            this.visible = true;
        },
        // 选择图片
        handleChange({ fileList }) {
            this.fileList = fileList;
        },
        // 选择图片
        handleChange1({ fileList }) {
            this.fileList1 = fileList;
            console.log(this.fileList1,'filelist')
        },
        // 选择图片
        handleChange2({ fileList }) {
            this.fileList2 = fileList;
        },
        // 确定添加、修改
        async handleOk(){
            let _this = this
            _this.confirmLoading = true
            if(_this.item.name == ''){
                _this.$message.warning('请输入商品名称');
                return
            }
            if(_this.item.cateId === undefined){
                _this.$message.warning('请选择商品分类');
                return
            }
            // if(_this.item.colorId === undefined){
            //     _this.$message.warning('请选择商品颜色');
            //     return
            // }
            _this.confirmLoading = true;
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', _this.item.id);
            formData.append('name', _this.item.name);
            formData.append('cateId', _this.item.cateId);
            // formData.append('colorId', _this.item.colorId);
            formData.append('sort', _this.item.sort);
            formData.append('status', _this.item.status);
            if(_this.fileList.length > 0 && !_this.fileList[0].isUrl){
                formData.append('file',_this.fileList[0].originFileObj)
            }
            updateGoodsGeneral(formData)
            .then(async res=>{
                _this.confirmLoading = false
                if(res.success){
                    await _this._updateGoodsPictureEvn('0',res.data.id)
                    await _this._updateGoodsPictureEvn('1',res.data.id)
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.item.id == '' ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除
        del(item){
            let _this = this;
            const params = {
                'id': item.id,
                'name': item.name,
                'cateId': item.cateId,
                'isDelete': '1'
            }
            var formData = new FormData();
            formData.append('brandId', _this.brandId);
            formData.append('id', item.id);
            formData.append('name', item.name);
            formData.append('cateId', item.cateId);
            formData.append('isDelete', '1');
            updateGoodsGeneral(formData)
            .then(res => {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 跳转详情
        detail(item){
            this.$router.push({path: '/newMall/goodDetail',query: { 'item': JSON.stringify(item)}});
        },
        _queryGoodsPicture(id,type){
            let _this = this;
            const params = {
                'brandId': _this.brandId,
                'goodsId': id,
                'type': type,
            }
            queryGoodsPicture(params)
            .then(res => {
                if(res.success){
                    var list = [];
                    var array = res.data;
                    for (let index = 0; index < array.length; index++) {
                        const item = array[index];
                        list.push({
                            'uid': item.id,
                            'id': item.id,
                            'url': item.imageUrl,
                            'goodsId': item.goodsId,
                            'type': item.type,
                            'status':'done',
                            'name':'image.png'
                        })
                    }
                    if(type == '1'){
                        _this.fileList1 = list;
                        _this.carouselPicture = res.data;
                    }else{
                        _this.fileList2 = list;
                        _this.detailsPicture = res.data;
                    }
                }else{

                }
            })
        },
        async handlePreview(file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        handleCancel() {
            this.previewVisible = false;
        },
        // 增删改商品图片
        async _updateGoodsPictureEvn(type,id){
            let _this = this;
            let add = []; // 删除
            let del = []; // 新增
            var array = [];
            var updateArray = [];
            if(type == '1'){
                array = _this.carouselPicture
                updateArray = _this.fileList1
            }else{
                array = _this.detailsPicture
                updateArray = _this.fileList2
            }
            del = array.filter(x => !updateArray.some(y => y.id === x.id));
            console.log(del,'oldArr')
            for (let index = 0; index < updateArray.length; index++) {
                const item = updateArray[index];
                if(!item.id){
                    add.push(item);
                }
            }
            console.log(add,'add');
            // 添加
            if(add.length > 0){
                for (let index = 0; index < add.length; index++) {
                    const element = add[index];
                    const formData = new FormData();
                    formData.append('brandId',_this.brandId);
                    formData.append('goodsId',id);
                    formData.append('type',type);
                    formData.append('file',element.originFileObj)
                    await _this._updateGoodsPicture(formData);
                }
            }
            // 删除
            if(del.length > 0){
                for (let index = 0; index < del.length; index++) {
                    const element = del[index];
                    const formData = new FormData();
                    formData.append('brandId',_this.brandId);
                    formData.append('goodsId',id);
                    formData.append('type',type);
                    formData.append('isDelete',1);
                    formData.append('id',element.id)
                    await _this._updateGoodsPicture(formData);
                }
            }
        },
        _updateGoodsPicture(params){
            return new Promise((resolve,reject) => {
                updateGoodsPicture(params)
                .then(res => {
                    if(res.success){
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
    }
}

</script>
<style scoped>

</style>